import Request from 'luch-request'//npm下载引入luch-request
import DEV_CONFIG from '@/config/dev.env.js';
import api from '@/providers/API/api.js'
// import TEST_CONFIG from '@/config/test.env.js';
// import PROD_CONFIG from '@/config/prod.env.js';

const ENV_CONFIG = DEV_CONFIG //开发环境配置
// const ENV_CONFIG = TEST_CONFIG //测试环境配置
// const ENV_CONFIG = PROD_CONFIG //生产环境配置

const http = new Request({
	baseURL: ENV_CONFIG.SERVER_URL, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: {
		'Content-Type': 'application/json;',
	}
})
 
//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作

	// const token = uni.getStorageSync('token');
	const token = 'test1';
	const province =uni.getStorageSync('province')
	const city =uni.getStorageSync('city')
	console.log(config,'config')
	if (token) {
		config.header['Authorization'] = 'Bearer ' + token;
		config.header["tenant-id"] = 1;
		config.header["accept"] = '*/*'
		// if(config.url == api.getServiceManage){
		// 	config.header["id"] = 1
		// }
	}
	if(province){
		config.header['province']=encodeURIComponent(province)
		config.header['city']=encodeURIComponent(city)
	}
	if (config.method === 'POST') {
		config.data = JSON.stringify(config.data);
	}
	
	return config
}, error => {
	return Promise.resolve(error)
})
 
// 响应拦截器
http.interceptors.response.use((response) => {
	console.log(response.data,'data')
	if(response.data.msg!=''&&response.data.code!=0&&response.data.code!=1){
		uni.showToast({
			title: response.data.msg, //显示的文字 
			icon: 'none',
		})
	}
	if (response.data.code == 200){
		return Promise.reject(response)
	}else {
		return response.data
	}
}, (error) => {
	 // 超时处理
	 console.log(error,'error')
	let originalRequest = error.config
	if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
		Toast('请检查网络再重新连接')
		return Promise.reject('请检查网络再重新连接')
	}
	if (error.response) {
		return Promise.reject(error.response)
	}
})
export default http;
 